﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
using Microsoft.Win32;
using System.Windows;
using System.Xml;
using SHomeWorkshop.LunarConcept.Controls;
using SHomeWorkshop.LunarConcept.ModifingManager;
using System.Windows.Controls;
using System.Windows.Media;
using SHomeWorkshop.LunarConcept.Tools;

namespace SHomeWorkshop.LunarConcept.Commands
{
    /// <summary>
    /// 创建时间：2012年7月16日
    /// 创建者：  杨震宇
    /// 
    /// 主要用途：设置部件配色方案（前景、背景、边线[框]色）。一般用在将部件做成按钮状。
    /// ★★说明：关于自定义命令的实现，可参考“NewDocument”类的备注。
    /// </summary>
    public static class SetWidgetAsBubbleCommand
    {
        #region 构造方法=====================================================================================================

        /// <summary>
        /// ★②，修改静态构造方法名。
        /// </summary>
        static SetWidgetAsBubbleCommand()//类型构造器
        {
            //★③，修改两个字符串参数名。★④以及第三个参数的类型名。
            routedUICmd = new RoutedUICommand(
                "SetWidgetAsBubbleCommand",
                "SetWidgetAsBubbleCommand",
                typeof(SetWidgetAsBubbleCommand),//创建RoutedUICommand对象
                null);

            //如果需要挂接快捷键，请参考下面这段代码：
            //routedUICmd = new RoutedUICommand(
            //    "SaveDocumentCommand",
            //    "SaveDocumentCommand",
            //    typeof(SaveDocumentCommand),//创建RoutedUICommand对象
            //    new InputGestureCollection() 
            //    { 
            //        //★⑤，修改此处三个参数，以便挂接快捷键。
            //        new KeyGesture(Key.S,ModifierKeys.Control,"Ctrl+S")
            //    });

            cmdBinding.Command = routedUICmd;
            cmdBinding.CanExecute += new CanExecuteRoutedEventHandler(cmdBinding_CanExecute);
            cmdBinding.Executed += new ExecutedRoutedEventHandler(cmdBinding_Executed);
        }

        #endregion

        #region 字段与属性===================================================================================================

        private static CommandBinding cmdBinding = new CommandBinding();
        /// <summary>
        /// 用在主窗口CommandBindings集合中的命令绑定。
        /// 
        /// 它的Command是RoutedUICommand。
        /// ——因此，RoutedUICommand是否可以运行将由CmdBinding的CanExecute事件决定。
        /// ——而且，RoutedUICommand的执行也是通过CmdBinding的Execute事件来进行的。
        /// </summary>
        public static CommandBinding CmdBinding
        {
            get { return cmdBinding; }
        }

        private static RoutedUICommand routedUICmd;
        /// <summary>
        /// [只读静态属性]表示在WPF系统中注册的一个RoutedUICommand。
        /// ——必须和CommandBinding配合才能使用。
        ///     CommandBinding要添加到主窗口的CommandBindings集合中；
        ///     RoutedUICommand则要向WPF系统注册。
        ///     
        /// ★说明：使用静态属性是因为这样在Xaml代码中比较便于绑定。
        /// </summary>
        public static RoutedUICommand RoutedUICmd
        {
            get { return routedUICmd; }
        }

        #endregion

        #region 方法=========================================================================================================

        static void cmdBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            //★⑧，修改此方法的实现。
            //if (Globals.MainWindow == null)
            //{
            //    e.CanExecute = false; return;
            //}

            //EditorManager manager = Globals.MainWindow.EditorManager;

            //if (manager == null)
            //{
            //    e.CanExecute = false; return;
            //}

            //if (manager.GetSelectedWidgetsCount() <= 0)
            //{
            //    e.CanExecute = false; return;
            //}

            e.CanExecute = true; return;
        }

        static void cmdBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            //★⑦，修改此方法的实现。

            LunarMessage.Warning(Execute(e.Parameter as string));
        }

        /// <summary>
        /// [公开静态方法]即使此命令处于禁用状态，也可以通过代码调用此方法来执行特定任务！！！
        /// 
        /// 当被绑定的命令被调用（触发）时，会引发cmdBinding_Executed事件。
        /// 在cmdBinding_Executed事件处理器方法中已添加了调用Execute()方法的代码。
        /// 
        /// ——因此，触发命令，就相当于调用此方法！！！
        /// </summary>
        /// <param name="newBackColorName">注意，必须是预定义的某个资源在BrushManager中的映射属性名。
        /// 定义在\Tools\CustomBrushes\_RectangleGlassButtons.xaml和\Tools\CustomBrushes\_RoundGlassButtons.xaml中。</param>
        public static string Execute(string newBackColorName)
        {
            if (string.IsNullOrEmpty(newBackColorName)) return "　　未指定预定义部件配色方案的名称。";
            if (Globals.MainWindow == null) return "　　未找到Globals.MainWindow。";
            EditorManager manager = Globals.MainWindow.EditorManager;
            if (manager == null) return "　　未找到页面管理器。";

            List<Widgets.Widget> selectedWidgets = manager.GetSelectedWidgetsList();
            if (selectedWidgets.Count <= 0) return "　　未选定任何部件。";

            ModifingInfo info = new ModifingInfo();
            manager.GetSelectedPageEditorStatus(info);
            manager.GetSelectedWidgetStatus_Old(info);
            manager.GetSelectedWidgetStatus_New(info);

            info.ModifingDescription = "设置矩形为气泡式";

            List<Widgets.RectangleWidget> selRectangles = new List<Widgets.RectangleWidget>();

            foreach (Widgets.Widget w in selectedWidgets)
            {
                Widgets.RectangleWidget rw = w as Widgets.RectangleWidget;
                if (rw != null) selRectangles.Add(rw);
            }

            if (selRectangles.Count <= 0) return "　　此功能仅适用于矩形部件！";

            ModifingItem<Action, ModifingInfo> mi = new ModifingItem<Action, ModifingInfo>(info);

            //TODO: 这个功能暂时做得简单些，边框统一为０，边线色统一为透明色，前景色统一为白色。

            Brush newBackColor = BrushManager.GetBrush(newBackColorName);
            if (newBackColor == null) return "　　在程序预定义的画刷集中未找到指定名称的背景画刷，无法继续。";
            VisualBrush vBsh = newBackColor as VisualBrush;

            if (vBsh == null)
            {
                foreach (Widgets.RectangleWidget w in selRectangles)
                {
                    if (w.WidgetBackColor != BrushManager.GetBrush(newBackColorName))
                    {
                        Action actSetBackColor = new Action(w.MasterEditor.Id, w.Id, w.GetType().Name, XmlTags.WidgetBackColor,
                            BrushManager.GetName(w.WidgetBackColor), newBackColorName);
                        w.WidgetBackColor = BrushManager.GetBrush(newBackColorName);
                        mi.AddAction(actSetBackColor);
                    }

                    if (w.WidgetForeColor != Brushes.White)
                    {
                        Action actSetForeColor = new Action(w.MasterEditor.Id, w.Id, w.GetType().Name, XmlTags.WidgetForeColor,
                            BrushManager.GetName(w.WidgetForeColor), BrushManager.GetName(Brushes.White));
                        w.WidgetForeColor = Brushes.White;
                        mi.AddAction(actSetForeColor);
                    }

                    if (w.WidgetLineColor != Brushes.Transparent)
                    {
                        Action actSetLineColor = new Action(w.MasterEditor.Id, w.Id, w.GetType().Name, XmlTags.WidgetLineColorTag,
                            BrushManager.GetName(w.WidgetLineColor), BrushManager.GetName(Brushes.Transparent));
                        w.WidgetLineColor = Brushes.Transparent;
                        mi.AddAction(actSetLineColor);
                    }

                    if (w.WidgetLineWidth != 0)
                    {
                        Action actSetLineWidth = new Action(w.MasterEditor.Id, w.Id, w.GetType().Name, XmlTags.WidgetLineWidthTag,
                            w.WidgetLineWidth.ToString(), 0.ToString());
                        w.WidgetLineWidth = 0;
                        mi.AddAction(actSetLineWidth);
                    }

                    if (w.TextAreaAlignment != Enums.TextAreaAlignment.Center)
                    {
                        Action actTextAreaAlignment = new Action(w.MasterEditor.Id, w.Id, w.GetType().Name, XmlTags.TextAreaAlignmentTag,
                            w.TextAreaAlignment.ToString(), Enums.TextAreaAlignment.Center.ToString());
                        w.TextAreaAlignment = Enums.TextAreaAlignment.Center;
                        mi.AddAction(actTextAreaAlignment);
                    }

                    if (w.FixTextWidth != false)
                    {
                        //气泡不允许“文本自动折行”
                        Action actFixTextwidth = new Action(w.MasterEditor.Id, w.Id, w.GetType().Name, XmlTags.FixTextWidthTag,
                            w.FixTextWidth.ToString(), false.ToString());
                        w.FixTextWidth = false;
                        mi.AddAction(actFixTextwidth);
                    }
                }
            }
            else
            {
                //气泡画刷

                foreach (Widgets.RectangleWidget w in selRectangles)
                {
                    if (w.WidgetBackColor != BrushManager.GetBrush(newBackColorName))
                    {
                        Action actSetBackColor = new Action(w.MasterEditor.Id, w.Id, w.GetType().Name, XmlTags.WidgetBackColor,
                            BrushManager.GetName(w.WidgetBackColor), newBackColorName);
                        w.WidgetBackColor = BrushManager.GetBrush(newBackColorName);
                        mi.AddAction(actSetBackColor);
                    }

                    if (newBackColorName.Contains("Hollow"))//空心气泡，默认黑字。
                    {
                        if (w.WidgetForeColor != Brushes.Black)
                        {
                            Action actSetForeColor = new Action(w.MasterEditor.Id, w.Id, w.GetType().Name, XmlTags.WidgetForeColor,
                                BrushManager.GetName(w.WidgetForeColor), BrushManager.GetName(Brushes.Black));
                            w.WidgetForeColor = Brushes.Black;
                            mi.AddAction(actSetForeColor);
                        }
                    }
                    else
                    {
                        if (w.WidgetForeColor != Brushes.White)//实心气泡，默认白字。
                        {
                            Action actSetForeColor = new Action(w.MasterEditor.Id, w.Id, w.GetType().Name, XmlTags.WidgetForeColor,
                                BrushManager.GetName(w.WidgetForeColor), BrushManager.GetName(Brushes.White));
                            w.WidgetForeColor = Brushes.White;
                            mi.AddAction(actSetForeColor);
                        }
                    }

                    Brush baseBsh = BrushManager.GetVisualBrushBaseBrush(vBsh);

                    if (w.WidgetLineColor != Brushes.Transparent)
                    {
                        Action actSetLineColor = new Action(w.MasterEditor.Id, w.Id, w.GetType().Name, XmlTags.WidgetLineColorTag,
                            BrushManager.GetName(w.WidgetLineColor), BrushManager.GetName(Brushes.Transparent));
                        w.WidgetLineColor = Brushes.Transparent;
                        mi.AddAction(actSetLineColor);
                    }

                    if (w.WidgetLineWidth != 0)
                    {
                        Action actSetLineWidth = new Action(w.MasterEditor.Id, w.Id, w.GetType().Name, XmlTags.WidgetLineWidthTag,
                            w.WidgetLineWidth.ToString(), 1.ToString());
                        w.WidgetLineWidth = 1;
                        mi.AddAction(actSetLineWidth);
                    }

                    if (w.TextAreaAlignment != Enums.TextAreaAlignment.Center)
                    {
                        Action actTextAreaAlignment = new Action(w.MasterEditor.Id, w.Id, w.GetType().Name, XmlTags.TextAreaAlignmentTag,
                            w.TextAreaAlignment.ToString(), Enums.TextAreaAlignment.Center.ToString());
                        w.TextAreaAlignment = Enums.TextAreaAlignment.Center;
                        mi.AddAction(actTextAreaAlignment);
                    }

                    if (w.FixTextWidth != false)
                    {
                        //气泡不允许“文本自动折行”
                        Action actFixTextwidth = new Action(w.MasterEditor.Id, w.Id, w.GetType().Name, XmlTags.FixTextWidthTag,
                            w.FixTextWidth.ToString(), false.ToString());
                        w.FixTextWidth = false;
                        mi.AddAction(actFixTextwidth);
                    }
                }
            }

            manager.RegisterModifingItem(mi);
            return string.Empty;
        }

        #endregion
    }
}
